/*
 * ============================================================================
 *
 *       Filename:  compress.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2015年04月27日 17时49分20秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <zlib.h>

int my_compress(Bytef *input, uLong insize,
	Bytef **pout, int *poutsize)
{
	uLong destLen = compressBound(insize);
	*pout = malloc(destLen);
	if(*pout == NULL) {
		printf("file %s line %d malloc failed: %s(%d)\n",
			__FILE__, __LINE__, strerror(errno), errno);
		return -1;
	}

	int res = compress(*pout, &destLen, input, insize); 
	if(res == Z_BUF_ERROR) {
		free(*pout);
		printf("Buffer was too small!\n");
		return -1;
	}
	if(res ==  Z_MEM_ERROR){
		free(*pout);
		printf("Not enough memory for compression!\n");
		return -1;
	}
	*poutsize = destLen;

	return 0;
}

int my_uncompress(Bytef *input, uLong insize, Bytef **pout, uLongf *poutsize)
{
	int ret = uncompress(*pout, poutsize, input, insize); 
	if(ret != Z_OK) {
		printf("uncompress failed: %d "
			"(Z_BUF_ERROR: %d, Z_MEM_ERROR: %d,Z_DATA_ERROR:%d)\n",
			ret, Z_BUF_ERROR, Z_MEM_ERROR, Z_DATA_ERROR);
		return -1;
	}

	return 0;
}



int main ()
{
	unsigned char test_string[] = "=============================This is test tring!======================================================================================";
	unsigned long int inlen = sizeof(test_string);
	unsigned long int outlen = 0;
	unsigned char *out_str = NULL;
	my_compress(test_string, inlen, &out_str, &outlen);
	int i;
	printf("原长度:%d,压缩后的长度:%d\n", inlen,outlen);
	printf("[");
	for (i = 0; i < outlen; i++) {
		printf("%c", out_str[i]);
	}
	printf("]\n");
	FILE *file = fopen("/tmp/compress", "w");
	fwrite(out_str, outlen, 1, file);
	fclose(file);

	unsigned char *uncom_string;
	unsigned long int uncom_len = 0;
	my_uncompress(out_str, outlen, &uncom_string, &uncom_len);
	printf("uncompres:%s, len:%d\n", uncom_string, uncom_len);





}
